package com.example.jx;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import com.example.application.QZApplication;

import android.content.Context;
import android.os.Environment;

/**
 * 緩存操作
 * 
 * @author Administrator
 *
 */
public class FileUtils {

	// 如果文件不存在则创建文件
	public final static int CREATE_FILE_IFNO = 1;
	// 如果文件不存在也不创建
	public final static int NUCREATE_FILE_IFNO = 0;

	/**
	 * 将数据缓存到本地
	 * 
	 * @param serializable
	 * @param fileName
	 * 
	 * @return T:操作成功 F:操作失败
	 */
	public static boolean saveObjectToChache(Serializable serializable,
			String fileName) {

		FileOutputStream fOutputStream = null;
		ObjectOutputStream objectOutputStream = null;

		try {
			fOutputStream = QZApplication.getInstance().openFileOutput(
					fileName, Context.MODE_PRIVATE);
			objectOutputStream = new ObjectOutputStream(fOutputStream);
			objectOutputStream.writeObject(serializable);
			objectOutputStream.flush();// 写入
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			try {
				objectOutputStream.close();
				fOutputStream.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	/**
	 * 读取缓存值
	 * 
	 * @param fileName
	 * @return
	 */
	public static Serializable readObjectFromChache(String fileName) {
		FileInputStream fileInputStream = null;
		ObjectInputStream objectInputStream = null;

		try {
			fileInputStream = QZApplication.getInstance().openFileInput(
					fileName);
			objectInputStream = new ObjectInputStream(fileInputStream);
			return (Serializable) objectInputStream.readObject();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				objectInputStream.close();
				fileInputStream.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	/**
	 * 获取项目文件夹
	 * 
	 * @param fileName
	 * @param mode
	 *            0：不创建 1：如果不存在则创建
	 * @return
	 */
	public static File getApplicationFile(String fileName, int mode) {
		File temp = new File(Environment.getExternalStorageDirectory()
				+ "/qzzm/" + fileName);
		switch (mode) {
		case CREATE_FILE_IFNO:
			if (!temp.exists()) {
				temp.mkdir();
			}
			return temp;
		case NUCREATE_FILE_IFNO:
			return temp;
		default:
			break;
		}
		return null;
	}

}
